package com.gw.yunke.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.github.pagehelper.PageInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class MybatisConfig {

    @Resource
    private Environment environment;

    @Bean
    public DataSource druidDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(environment.getProperty("spring.datasource.url"));
        dataSource.setDriverClassName(environment.getProperty("spring.datasource.driver-class-name"));
        dataSource.setUsername(environment.getProperty("spring.datasource.username"));
        dataSource.setPassword(environment.getProperty("spring.datasource.password"));
        return dataSource;
    }

    @Bean
    public PageInterceptor pageInterceptor() {
        PageInterceptor pageInterceptorBean = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("pageSizeZero","true");
        pageInterceptorBean.setProperties(properties);
        return pageInterceptorBean;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() {
        System.out.println("设置mybatis");
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        Interceptor[] interceptors = new Interceptor[]{pageInterceptor()};
        bean.setPlugins(interceptors);
        bean.setDataSource(druidDataSource());
        bean.setTypeAliasesPackage(environment.getProperty("spring.mybatis.typeAliasesPackage"));

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            System.out.println(environment.getProperty("spring.mybatis.mapperLocations"));
            bean.setMapperLocations(resolver.getResources(environment.getProperty("spring.mybatis.mapperLocations")));

            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
